package com.zhongxi.guoyuan.view.user.gift;

import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.GiftAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseActivity;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.gift.GiftRuleResult;
import com.zhongxi.guoyuan.entity.gift.NoviceItemData;
import com.zhongxi.guoyuan.entity.gift.NoviceItemResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.utils.CommonTool;
import com.zhongxi.guoyuan.utils.GlideRoundTransform;
import com.zhongxi.guoyuan.view.HtmlActivity;
import com.zhongxi.guoyuan.view.play.MoneyTreeActivity;
import com.zhongxi.guoyuan.view.update.UpdateActivity;
import com.zhongxi.guoyuan.widget.sliding.NoScrollListView;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class NewPersonGiftActivity extends BaseActivity implements View.OnClickListener {

    private NoScrollListView lvList;
    private String type;
    private ImageView ivLogo;
    private TextView tvPhone;
    private TextView tvTime;
    private TextView tvMeibi;
    private TextView tvIdentify;
    private TextView tvUpdate;
    private List<NoviceItemData> data = new ArrayList<NoviceItemData>();
    private GiftAdapter adapter;
    private Map<String, String> map = new HashMap<String, String>();
    private GiftRuleResult result;
    private ImageView ivImg;
    private NoviceItemResult noviceItemResult;
    public static final int requestGift=10;
    public static final int requestMeiBiCode=20;
    @Override
    protected void initView() {
        super.initView();
        setContentView(R.layout.activity_new_person_gift);
        initTitle();
        tvTitle.setText("美容大礼包");
        lvList = (NoScrollListView) findViewById(R.id.lvList);
        ivLogo = (ImageView) findViewById(R.id.ivLogo);
        tvPhone = (TextView) findViewById(R.id.tvPhone);
        tvTime = (TextView) findViewById(R.id.tvTime);
        tvMeibi = (TextView) findViewById(R.id.tvMeibi);
        tvIdentify = (TextView) findViewById(R.id.tvIdentify);
        tvUpdate = (TextView) findViewById(R.id.tvUpdate);
        ivImg = (ImageView) findViewById(R.id.ivImg);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new GiftAdapter(context, data);
        lvList.setAdapter(adapter);
        initInfo();
        type = "rule";
        getServer(Url.RULE_TPL, null, "", false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try {
            if ("rule".equals(type)) {
                result = gson.fromJson(response, GiftRuleResult.class);
                MyApplication.getInstance().setSpValue(result.getSafeobj());
                if(null!=result.getData()&&!"".equals(result.getData())){
                    if (null != result.getData().getImages() && !"".equals(result.getData().getImages())) {
                        Glide.with(context)
                                .load(Url.IMG_URL+result.getData().getImages())
                                .placeholder(R.mipmap.iv_gift)
                                .transform(new GlideRoundTransform(context, 20))
                                .into(ivLogo);
                    }
                }
                getItem();
            } else if ("item".equals(type)) {
                noviceItemResult = gson.fromJson(response, NoviceItemResult.class);
                MyApplication.getInstance().setSpValue(noviceItemResult.getSafeobj());
                data.clear();
                if(null!=noviceItemResult.getDate()&&noviceItemResult.getDate().size()>0){
                    data.addAll(noviceItemResult.getDate());
                }
                adapter.notifyDataSetChanged();
                getProject();
            }else if("receiver".equals(type)){
                //成功领取大礼包
                showStatusDialog(5, 0);
                getItem();
            }else if("project".equals(type)){
                NoviceItemResult itemResult = gson.fromJson(response, NoviceItemResult.class);
                MyApplication.getInstance().setSpValue(noviceItemResult.getSafeobj());
                if(null!=itemResult.getData()&&itemResult.getData().size()>0){
                    data.addAll(itemResult.getData());
                }
                adapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse res = gson.fromJson(response, BaseResponse.class);
            if(null!=res.getSafeobj()&&!"".equals(res.getSafeobj())){
                MyApplication.getInstance().setSpValue(res.getSafeobj());
            }
            if("receiver".equals(type)){
                if (res.getCode()==1000){
                    showShortToast("参数错误 《各接口相关》");
                }
                showShortToast("条件不满足，请查看领取时间或美币是否充足");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * 初始化用户数据
     *
     */
    private void initInfo() {
        try {
            if (null != MyApplication.getInstance().getAvatar() && !"".equals(MyApplication.getInstance().getAvatar())) {
                Glide.with(context).load(Url.BASE_URL+MyApplication.getInstance().getAvatar()).transform(new GlideRoundTransform(context, 20)).placeholder(R.mipmap.iv_eg).into(ivImg);
            }
            if (null != MyApplication.getInstance().getPhone() && !"".equals(MyApplication.getInstance().getPhone())) {
                tvPhone.setText("注册手机：" + MyApplication.getInstance().getPhone());
            } else {
                tvPhone.setText("");
            }
            if (null != MyApplication.getInstance().getRegisterTime() && !"".equals(MyApplication.getInstance().getRegisterTime())) {
                tvTime.setText("注册时间：" + MyApplication.getInstance().getRegisterTime());
            } else {
                tvTime.setText("注册时间：");
            }
            if (null != MyApplication.getInstance().getInnerCurrency() && !"".equals(MyApplication.getInstance().getInnerCurrency())) {
                tvMeibi.setText(MyApplication.getInstance().getInnerCurrency() + "美币");
            } else {
                tvMeibi.setText("*美币");
            }
            if(MyApplication.getInstance().isPrivilege()){
                tvIdentify.setText("身份证：权益会员");
                tvUpdate.setVisibility(View.GONE);
            }else{
                tvIdentify.setText("身份证：普通会员");
                tvUpdate.setVisibility(View.VISIBLE);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 新手礼包项目
     */
    private void getItem() {
        type = "item";
        getServer(Url.NOVICE_ITEM, null, "", false, null, "get");
    }

    /**
     *活动礼包项目
     */
    private void getProject(){
        type = "project";
        getServer(Url.FESTIVALITEM, null, "", false, null, "get");
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        ivBack.setOnClickListener(this);
        tvUpdate.setOnClickListener(this);
        ivLogo.setOnClickListener(this);
        lvList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(null!=data.get(position).getShareKey()&&!"".equals(data.get(position).getShareKey())){
                    Intent intent = new Intent(context, GiftDetailActivity.class);
                    intent.putExtra("sharekey", data.get(position).getShareKey());
                    intent.putExtra("status",data.get(position).getStatus());
                    startActivityForResult(intent,requestGift);
                }else{
                    switch (data.get(position).getStatus()){
                            case "0":   //待领取
                                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                                if(!CommonTool.TimeCompare(data.get(position).getStime(), sdf.format(new Date(System.currentTimeMillis())))){
                                    showStatusDialog(3, position);//领取时间未到
                                }else if(null!=data.get(position).getCurrencytype()&&!"".equals(data.get(position).getCurrencytype())){
                                    if("1".equals(data.get(position).getCurrencytype())){   //1.美币  2.银币
                                        if("".equals(MyApplication.getInstance().getInnerCurrency())||Integer.parseInt(MyApplication.getInstance().getInnerCurrency())<
                                                Integer.parseInt(data.get(position).getCurrencynum())){
                                            showStatusDialog(4, position);//美币不足
                                        }else{
                                            showStatusDialog(0, position);//领取红包
                                        }
                                    }else{
                                        if("".equals(MyApplication.getInstance().getSilver())||Integer.parseInt(MyApplication.getInstance().getSilver())<
                                                Integer.parseInt(data.get(position).getCurrencynum())){
                                            showStatusDialog(6, position);//银币不足
                                        }else{
                                            showStatusDialog(0, position);//领取红包
                                        }
                                    }
                                }
                            break;
                        case "1":
                            showStatusDialog(1, position);
                            break;
                        case "2":
                            showStatusDialog(2, position);
                            break;
                    }
                }
            }
        });
    }

    /**
     * @param status
     * @param position
     */
    private void showStatusDialog(int status, final int position) {
        LayoutInflater inflater = LayoutInflater.from(this);
        LinearLayout layout = (LinearLayout) inflater.inflate(R.layout.dialog_gift, null);
        final AlertDialog dialog = new AlertDialog.Builder(context).create();
        dialog.show();
        dialog.getWindow().setContentView(layout);
        TextView tvTitle= (TextView) layout.findViewById(R.id.tvTitle);
        TextView tvName= (TextView) layout.findViewById(R.id.tvName);
        TextView tvTips = (TextView) layout.findViewById(R.id.tvTips);
        TextView tvQuit = (TextView) layout.findViewById(R.id.tvQuit);
        TextView tvSure = (TextView) layout.findViewById(R.id.tvSure);
        ImageView ivImg = (ImageView) layout.findViewById(R.id.ivImg);
        ImageView ivCancel = (ImageView) layout.findViewById(R.id.ivCancel);
        tvTitle.setText(data.get(position).getTitle());
        tvName.setText(data.get(position).getName());
        //取消/放弃
        tvQuit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        ivCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        switch (status){
            case 0:
                if (data.get(position).getCurrencytype().equals("1")){
                    tvTips.setText("恭喜您，您的美币足够领取大礼包！");
                }else {
                    tvTips.setText("恭喜您，您的银币足够领取大礼包！");
                }

                tvQuit.setVisibility(View.GONE);
                tvSure.setVisibility(View.VISIBLE);
                tvSure.setText("确认领取");
                tvSure.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //领取礼包
                        type = "receiver";
                        map.put("giftid",data.get(position).getId());
                        map.put("gtype", data.get(position).getGifttype());
                        map.put("currencytype", data.get(position).getCurrencytype());
                        map.put("currencynum", data.get(position).getCurrencynum());
                        getServer(Url.RECEIVE_GIFT, map, "", false, null, "post");
                        dialog.dismiss();
                    }
                });
                break;
            case 1:
                ivImg.setImageResource(R.mipmap.has_get);
                tvTips.setText("亲，您已经领过大礼包了哟！");
                tvQuit.setText("好，我知道了！");
                tvSure.setVisibility(View.GONE);
                tvQuit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                break;
            case 2:
                tvTips.setText("很遗憾！您的该项大礼包过期了！");
                tvQuit.setText("好，我知道了！");
                tvSure.setVisibility(View.GONE);
                tvQuit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                break;
            case 3:
                ivImg.setImageResource(R.mipmap.iv_time);
                tvTips.setText("抱歉，领取时间还没到，请您耐心等待！");
                tvQuit.setText("再等等");
                tvSure.setVisibility(View.GONE);
                tvQuit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                break;
            case 4:
                ivImg.setImageResource(R.mipmap.iv_no_enough);
                tvTips.setText("非常抱歉！您的美币不足，请每日\"摇美币\"或分享赚美币哦！");
                tvQuit.setText("去摇美币");
                tvSure.setVisibility(View.GONE);
                tvQuit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent=new Intent(NewPersonGiftActivity.this,MoneyTreeActivity.class);
                        startActivityForResult(intent,requestMeiBiCode);
                        dialog.dismiss();
                    }
                });
                break;
            case 5:
                ivImg.setImageResource(R.mipmap.has_get);
                tvTips.setText("恭喜您！这个礼包已经被领取过了！");
                tvQuit.setText("好，我知道了！");
                tvSure.setVisibility(View.GONE);
                tvQuit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                break;
            case 6:
                ivImg.setImageResource(R.mipmap.iv_no_enough);
                tvTips.setText("非常抱歉！您的银币不足，请先到“返银超市”购买商品获得银币吧！");
                tvQuit.setText("确认");
                tvSure.setVisibility(View.GONE);
                tvQuit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                });
                break;
//            case 7:
//                tvTips.setText("恭喜您，您的银币足够领取大礼包！");
//                tvQuit.setVisibility(View.GONE);
//                tvSure.setVisibility(View.VISIBLE);
//                tvSure.setText("确认领取");
//                tvSure.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        //领取礼包
//                        type = "receiver";
//                        map.put("giftid",data.get(position).getId());
//                        map.put("gtype", "0");
//                        map.put("currencytype", data.get(position).getCurrencytype());
//                        map.put("currencynum", data.get(position).getCurrencynum());
//                        getServer(Url.RECEIVE_GIFT, map, null, false, null, "post");
//                        dialog.dismiss();
//                    }
//                });
//                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ivBack:
                finish();
                break;
            case R.id.tvUpdate:
                startAct(UpdateActivity.class);
                break;
            case R.id.ivLogo:
                Intent intent = new Intent(context, HtmlActivity.class);
                intent.putExtra("content", result.getData().getDescription());
                startActivity(intent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==requestGift&&resultCode==GiftDetailActivity.resultGift){
            getItem();
        }else if (requestCode==requestMeiBiCode&&resultCode==MoneyTreeActivity.resultMeiBiCode){
            initData();
        }
    }
}
